package net.loonggg.bar;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

import net.loonggg.bar.SideBar.OnTouchingLetterChangedListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.activity.HomeActivity;
import com.op.teachingliteapp.fragment.course.CourseFragment;

public class MainFragment extends Fragment {
	public static int TEXT_SIZE;
	public static float RATIO;
	private HashMap<String, Integer> selector;// 存放含有索引字母的位置
	private ArrayList<String> judge = new ArrayList<String>();
	private ListView listView;
	private TextView tv_show;
	private Context context;
	private ListViewAdapter adapter;
	private SideBar sideBar;
	private TextView tv;
	private CheckBox checkBox;
	private StringBuffer checkCourseName = new StringBuffer();
	private String[] indexStr = { "#", "A", "B", "C", "D", "E", "F", "G", "H",
			"I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U",
			"V", "W", "X", "Y", "Z" };
	private List<Course> Course = null;
	private List<Course> newCourse = new ArrayList<Course>();

	// 调用该方法时Fragment会被连接到它的父Activity上
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		// 获取对父Activity的引用
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_course_add, container, false);
	}

	public void onViewCreated(View view, Bundle savedInstanceState) {

		ListViewAdapter.courseList.clear();
		// 获取屏幕的大小
		DisplayMetrics displayMetrics = new DisplayMetrics();
		this.getActivity().getWindowManager().getDefaultDisplay()
				.getMetrics(displayMetrics);
		// 开发时使用的是2560*1600的平板，计算计算与你开发时设定的屏幕大小的纵横比
		int screenWidth = displayMetrics.widthPixels;
		int screenHeight = displayMetrics.heightPixels;
		float ratioWidth = (float) screenWidth / 2560;
		float ratioHeight = (float) screenHeight / 1600;
		RATIO = Math.min(ratioWidth, ratioHeight);

		// 根据上一步计算出来的最小纵横比来确定字体的大小(在2560*1600屏幕下字体大小设定为50)
		TEXT_SIZE = Math.round(60 * RATIO);

		// checkBox
		checkBox = (CheckBox) getActivity().findViewById(R.id.item_cb);

		super.onViewCreated(view, savedInstanceState);
		listView = (ListView) getActivity().findViewById(R.id.listView);
		// 提示所点击的字母文本
		tv_show = (TextView) getActivity().findViewById(R.id.dialog);
		tv_show.setTextSize(200 * RATIO);
		tv_show.setTextColor(Color.rgb(0, 0, 0));
		tv_show.setVisibility(View.GONE);

		adapter = new ListViewAdapter(getActivity(), newCourse);
		listView.setAdapter(adapter);
		// List<String> courseList = new ArrayList<String>();
		// courseList.add("Cyuyj");
		for (int i = 0; i < ListViewAdapter.courseList.size(); i++) {
			System.out.println(ListViewAdapter.courseList.get(i));
		}

		/*
		 * 是添加按钮所要实现的功能
		 */
		getActivity().findViewById(R.id.addBT).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {

						// checkCourseName清空
						checkCourseName.setLength(0);
						// 设置点击后将课程数组的内容添加进一个字符串中
						for (int i = 0; i < ListViewAdapter.courseList.size(); i++) {
							checkCourseName.append(ListViewAdapter.courseList
									.get(i) + "\n");
						}
						// 设置点击添加后弹出一个对话框
						dialog();
					}
				});
		getActivity().findViewById(R.id.emptyBT).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// checkCourseName清空
						checkCourseName.setLength(0);
						// 设置点击后清空CheckBox的选择情况
						checkBox.isChecked();
					}
				});
		// 添加item监听
		// listView.setOnItemClickListener(listener);
		sideBar = (SideBar) getActivity().findViewById(R.id.sidrbar);
		tv = (TextView) getActivity().findViewById(R.id.dialog);
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			public void onTouchingLetterChanged(String s) {
				Log.i("A", s);
				findItem(s, listView);

			}

		});
		sideBar.setTextView(tv);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getActivity();
		System.out.println(context);
		setData();
		String[] allNames = sortIndex(Course);
		sortList(allNames);
		selector = new HashMap<String, Integer>();
		for (int j = 0; j < indexStr.length; j++) {// 循环字母表，找出newCourse中对应字母的位置
			for (int i = 0; i < newCourse.size(); i++) {
				if (newCourse.get(i).getName().equals(indexStr[j])) {
					selector.put(indexStr[j], i);
					judge.add(indexStr[j]);
				}
			}

		}

	}

	/**
	 * 重新排序获得一个新的List集合
	 * 
	 * @param allNames
	 */
	private void sortList(String[] allNames) {
		for (int i = 0; i < allNames.length; i++) {
			if (allNames[i].length() != 1) {
				for (int j = 0; j < Course.size(); j++) {
					if (allNames[i].equals(Course.get(j).getPinYinName())) {
						Course p = new Course(Course.get(j).getName(), Course
								.get(j).getPinYinName());
						newCourse.add(p);
					}
				}
			} else {
				newCourse.add(new Course(allNames[i]));
			}
		}

	}

	/**
	 * 获取排序后的新数据
	 * 
	 * @param
	 * @return
	 */
	public String[] sortIndex(List<Course> newCourse) {
		TreeSet<String> set = new TreeSet<String>();
		// 获取初始化数据源中的首字母，添加到set中
		for (Course Course : newCourse) {
			set.add(StringHelper.getPinYinHeadChar(Course.getName()).substring(
					0, 1));
		}
		// 新数组的长度为原数据加上set的大小
		String[] names = new String[newCourse.size() + set.size()];
		int i = 0;
		for (String string : set) {
			names[i] = string;
			i++;
		}
		String[] pinYinNames = new String[newCourse.size()];
		for (int j = 0; j < newCourse.size(); j++) {
			newCourse.get(j).setPinYinName(
					StringHelper.getPingYin(newCourse.get(j).getName()
							.toString()));
			pinYinNames[j] = StringHelper.getPingYin(newCourse.get(j).getName()
					.toString());
		}
		// 将原数据拷贝到新数据中
		System.arraycopy(pinYinNames, 0, names, set.size(), pinYinNames.length);
		// 自动按照首字母排序
		Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
		return names;
	}

	/**
	 * 设置模拟数据
	 */
	private void setData() {
		Course = new ArrayList<Course>();
		Course p1 = new Course("AAA");
		Course.add(p1);
		Course p2 = new Course("AAAA");
		Course.add(p2);
		Course p3 = new Course("BBB");
		Course.add(p3);
		Course p4 = new Course("BBBB");
		Course.add(p4);
		Course p5 = new Course("C语言");
		Course.add(p5);
		Course p6 = new Course("CCCC");
		Course.add(p6);
		Course p7 = new Course("DDD");
		Course.add(p7);
		Course p8 = new Course("DDDD");
		Course.add(p8);
		Course p9 = new Course("EEE");
		Course.add(p9);
		Course p10 = new Course("EEEE");
		Course.add(p10);
		Course p11 = new Course("FFF");
		Course.add(p11);
		Course p12 = new Course("FFFF");
		Course.add(p12);
		Course p13 = new Course("GGG");
		Course.add(p13);
		Course p14 = new Course("GGGG");
		Course.add(p14);
		Course p15 = new Course("Html");
		Course.add(p15);
		Course p16 = new Course("HHHH");
		Course.add(p16);
		Course p17 = new Course("III");
		Course.add(p17);
		Course p18 = new Course("IIII");
		Course.add(p18);
		Course p19 = new Course("Java");
		Course.add(p19);
		Course p20 = new Course("计算机基础");
		Course.add(p20);
		Course p21 = new Course("KKK");
		Course.add(p21);
		Course p22 = new Course("KKKK");
		Course.add(p22);
		Course p23 = new Course("LLL");
		Course.add(p23);
		Course p24 = new Course("LLLL");
		Course.add(p24);
		Course p25 = new Course("面向对象");
		Course.add(p25);
		Course p26 = new Course("MMMM");
		Course.add(p26);
		Course p27 = new Course("NNN");
		Course.add(p27);
		Course p28 = new Course("NNNN");
		Course.add(p28);
		Course p29 = new Course("OOO");
		Course.add(p29);
		Course p30 = new Course("OOOO");
		Course.add(p30);
		Course p31 = new Course("PS");
		Course.add(p31);
		Course p32 = new Course("Php");
		Course.add(p32);
		Course p33 = new Course("QQQ");
		Course.add(p33);
		Course p34 = new Course("QQQQ");
		Course.add(p34);
		Course p35 = new Course("RRR");
		Course.add(p35);
		Course p36 = new Course("RRRR");
		Course.add(p36);
		Course p37 = new Course("SSS");
		Course.add(p37);
		Course p38 = new Course("SSSS");
		Course.add(p38);
		Course p39 = new Course("TTT");
		Course.add(p39);
		Course p40 = new Course("TTTT");
		Course.add(p40);
		Course p41 = new Course("UUU");
		Course.add(p41);
		Course p42 = new Course("UUUU");
		Course.add(p42);
		Course p43 = new Course("VVV");
		Course.add(p43);
		Course p44 = new Course("VVVV");
		Course.add(p44);
		Course p45 = new Course("WWW");
		Course.add(p45);
		Course p46 = new Course("WWWW");
		Course.add(p46);
		Course p47 = new Course("XXX");
		Course.add(p47);
		Course p48 = new Course("XXXX");
		Course.add(p48);
		Course p49 = new Course("YYY");
		Course.add(p49);
		Course p50 = new Course("YYYY");
		Course.add(p50);
		Course p51 = new Course("ZZZ");
		Course.add(p51);
		Course p52 = new Course("ZZZZ");
		Course.add(p52);

	}

	private void findItem(String s, ListView v) {
		int pos;
		for (int i = 0; i < judge.size(); i++) {
			if (s == judge.get(i)) {
				pos = selector.get(s);
				v.setSelection(pos + v.getHeaderViewsCount());
			}
		}

	}

	protected void dialog() {
		AlertDialog.Builder builder = new Builder(getActivity());
		builder.setMessage(checkCourseName);
		builder.setTitle("提示");
		builder.setNeutralButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// CourseFragment coursefragment=new CourseFragment();
				//
				// coursefragment.index=1;
				// Bundle nBundle = new Bundle();
				// nBundle.putStringArrayList("order",(ArrayList<String>)
				// ListViewAdapter.courseList);
				// coursefragment.setArguments(nBundle);
				FragmentManager fragmentManager = getFragmentManager();
				// 开始Fragment事务
				FragmentTransaction fTransaction = fragmentManager
						.beginTransaction();
				// //将Fragment添加到事务中，并指定一个TAG
				// fTransaction.add(coursefragment, "179521");
				// //提交Fragment事务
				// coursefragment=(CourseFragment)fragmentManager.findFragmentById(R.id.fragment_course);
				fTransaction.commit();
				// 清空课程List
				// ListViewAdapter.courseList.clear();
				getFragmentManager().beginTransaction().addToBackStack(null)
						.replace(R.id.main_show, new CourseFragment()).commit();
			}
		});
		builder.setNegativeButton("取消", null);
		builder.create();
		builder.show();
	}

}
